package org.lee.resbundleswing;

import org.lee.resbundleswing.res.UIConstants;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.Locale;
import java.util.ResourceBundle;

/**
 * ResourceBundleEx
 *
 * @author dralee
 * @date 2021-12-28 15:53:40
 **/
public class ResourceBundleEx extends JFrame {
    private ResourceBundle bundle;
    private JLabel flag;
    private JLabel lbl;
    private JMenu langMenu;
    private JRadioButtonMenuItem skMenuItem;
    private JRadioButtonMenuItem huMenuItem;

    public ResourceBundleEx() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        createMenuBar();
        flag = new JLabel();
        lbl = new JLabel();
        updateLanguage(new Locale("sk", "SK"));
        createLayout(lbl, flag);
        pack();

        setTitle(bundle.getString("name"));
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {
        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setHorizontalGroup(gl.createParallelGroup().addComponent(arg[0]).addComponent(arg[1]));
        gl.setVerticalGroup(gl.createSequentialGroup().addComponent(arg[0]).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(arg[1]));

    }

    private void updateLanguage(Locale locale) {
        bundle = ResourceBundle.getBundle("org.lee.resbundleswing.res.DocResources", locale);
        langMenu.setText(bundle.getString(UIConstants.LANG_MENU));
        skMenuItem.setText(bundle.getString(UIConstants.LANG_SK));
        huMenuItem.setText(bundle.getString(UIConstants.LANG_HU));
        flag.setIcon((Icon) bundle.getObject(UIConstants.FLAG));
        lbl.setText(bundle.getString(UIConstants.DESCRIPTION));
        setTitle(bundle.getString(UIConstants.NAME));
        pack();
    }

    private void createMenuBar() {
        JMenuBar menuBar = new JMenuBar();
        langMenu = new JMenu();
        langMenu.setMnemonic(KeyEvent.VK_F);

        ButtonGroup btnGroup = new ButtonGroup();
        skMenuItem = new JRadioButtonMenuItem("Slovak", true);
        btnGroup.add(skMenuItem);
        skMenuItem.addActionListener(e -> updateLanguage(new Locale("sk", "SK")));
        langMenu.add(skMenuItem);

        huMenuItem = new JRadioButtonMenuItem("Hungarian");
        btnGroup.add(huMenuItem);
        huMenuItem.addActionListener(e -> updateLanguage(new Locale("hu", "HU")));
        langMenu.add(huMenuItem);

        menuBar.add(langMenu);
        setJMenuBar(menuBar);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ResourceBundleEx().setVisible(true));
    }
}
